<template>
  <div>
    <!------------------------头部宠物列表------------------------------->
    <div style="display: flex; flex-wrap: wrap; gap: 10px;margin: 10px;" class="coverImg">
      <img class="pet_cover_imgs"
           v-for="(item, index) in petInfo"
           :key="index"
           :src="item.coverImg"
           @click="changeIndex(index)"/>
    </div>
    <!------------------------宠物信息------------------------------->
    <div class="healthInfo_contain">
      <div class="healthInfo_title">
        <div style="flex: 1 1 50%">
          <div style="display: flex;">
            <img :src=" petInfo[selected].coverImg "
                 style="height: 68px;width: 68px;object-fit: cover;border-radius: 40px;">
            <div style="padding-left: 3%;width: 84%;">
              <div style="font-weight: bold">{{ petInfo[selected].petName }}</div>
              <div class="pet_info_name" style="font-weight: normal;font-size: 12px;margin-top: 8px;color: #797979">
                品种:{{ petInfo[selected].specis }} 年龄:{{ petInfo[selected].age }}
                体重:{{ petInfo[selected].weight }}kg
              </div>
              <div class="pet_info_tag"
                   style="font-weight: normal;font-size: 12px;margin-top: 8px;color: #797979">健康评分：
                <StarFilled
                    v-for="(star, index) in Math.floor((petInfo[selected].vaccinationReconds + petInfo[selected].dewormingRecords)/3+1)"
                    :key="index"
                    style="color: #ffe223;"
                />
                <StarOutlined style="color: #ffe223 "/>
              </div>
            </div>
            <div style="font-size: 14px">
              <MehFilled style="color: #4CAF50"/>
              健康状况良好
            </div>
          </div>
        </div>
      </div>

      <div class="healthInfo_statistics">
        <div style="display: flex">
          <div style="width: 80%;font-weight: bold;font-size: 20px">健康数据统计</div>
          <div style="display: flex;flex: 1 1 30%">
            <div @click="query(7)" class="statistic_button">近7天</div>
            <div @click="query(30)" class="statistic_button">近30天</div>
            <input placeholder="自定义" :placeholder="自定义" v-model="queryData.dateRange"
                   @keyup.enter="query(queryData.dateRange)" class="statistic_input statistic_button"/>
          </div>
        </div>
        <div>
<!--          折线图放置-->
          <div ref="chart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      <div class="healthInfo_record">
        <div style="flex: 1">
          <div style="font-size: large;font-weight: bold">活动记录</div>
          <div style="padding-left: 200px;padding-bottom: 10px;padding-top: 10px;">
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <YuqueFilled/>
                晨间散步
              </div>
              <div style="flex: 1">{{ petActivity.walk }}分钟</div>
            </div>
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <GitlabFilled/>
                玩耍时间
              </div>
              <div style="flex: 1">{{ petActivity.play }}分钟</div>
            </div>
            <div style="display: flex;margin-top: 20px">
              <div style="flex: 1">
                <HighlightFilled/>
                训练时间
              </div>
              <div style="flex: 1">{{ petActivity.train }}分钟</div>
            </div>
          </div>
        </div>
        <div style="flex: 1">
          <div ref="chart2" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      <div class="healthInfo_remind">
        <div></div>
      </div>
    </div>
  </div>
</template>
<script>
import {getHealthCheckUpRecords, getPetActivityListAPI, getPetDrinkInfoAPI, getPetListAPI} from "@/api/petApi";
import {parseTime2, parseTime3} from "@/utils/timeUtil";
import {MehFilled, StarFilled, StarOutlined, YuqueFilled, GitlabFilled, HighlightFilled} from '@ant-design/icons-vue';
import * as echarts from 'echarts';


export default {
  name: "HealthInfo",
  components: {
    StarOutlined, StarFilled, YuqueFilled, MehFilled, GitlabFilled, HighlightFilled // 注册图标组件
  },
  data() {
    return {
      //柱状图配置信息
      option2: {
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} kg'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '饮水量 (ml)'
        },
        series: [
          {
            name: '日期',
            type: 'bar',
            data: []
          }
        ]
      },
      selected: 0,
      queryData: {
        petId: 1,
        dateRange: ''
      },
      petInfo: [
        {
          petId: 1,
          petName: "小白",
          specis: "狗",
          age: 3,
          weight: 15,
          gender: 1,
          dateOfBirth: 1621440000000,
          size: "中型",
          hairLength: "短毛",
          color: "白色",
          vaccinationReconds: 0,
          vaccinationRecond: '',
          dewormingRecords: 0,
          dewormingRecord: '',
          medicalHistory: "无",
          allergyHistory: "无",
          personalityTraits: "活泼粘人",
          dietaryHabits: "喜欢鸡肉和狗粮",
          activityPreferences: "喜欢跑步和玩球",
          sleepHabits: "喜欢睡觉",
          sportHabits: "习惯运动",
          coverImg: "http://localhost:8090/image/大狗 (2).png",
          mainImg: "http://localhost:8090/imag1312312313e/大狗 (2).png",
          imgs: "http://localhost:8090/image/大狗 (3).png;http://localhost:8090/image/大狗 (4).png;http://localhost:8090/image/大狗 (5).png"
        }
      ],
      option: {
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: '体重',
            type: 'line',
            data: [],
            smooth: true, // 平滑曲线
          },
        ],
      },
      petActivityList: [],
      petActivity: {},
      petDrinkList: [],
      petDrink: {}
    }
  },
  methods: {
    initChart() {
      // 初始化图表
      const chart = echarts.init(this.$refs.chart);
      // 设置配置项并渲染图表
      chart.setOption(this.option);
    },
    initChart2() {
      // 初始化图表
      const chart2 = echarts.init(this.$refs.chart2);
      // 设置配置项并渲染图表
      chart2.setOption(this.option2);
    },
    // 获取宠物健康状况
    query(queryDate) {
      this.option.series[0].data = [];
      this.option.xAxis.data = [];
      this.queryData.dateRange = queryDate;
      getHealthCheckUpRecords(this.queryData).then(res => {
        // 确保返回的数据是有效的
        if (res && res.data && Array.isArray(res.data)) {
          // 确保 series 和 xAxis 的数据结构已初始化
          this.option.series = this.option.series || [{data: []}];
          this.option.xAxis = this.option.xAxis || [{data: []}];

          // 从数组末尾开始向前遍历
          for (let i = 0; i < res.data.length - 1; i++) {
            const item = res.data[i];
            item.createdAt = parseTime3(item.createdAt); // 解析时间

            // 将数据推入对应的数组
            this.option.series[0].data.push(item.weight);
            this.option.xAxis.data.push(item.createdAt);
          }
        }
        this.initChart();
      });
    },
    getPetActivities() {
      getPetActivityListAPI().then(res => {
        this.petActivityList = res.data
        this.changeIndex(0)
      })
    },
    // 获取所有宠物的饮水信息
    getDrink() {
      getPetDrinkInfoAPI().then(res => {
        res.data.forEach(item => {
          item.createTime = parseTime3(item.createTime)
        })
        // 处理数据

        this.petDrinkList = res.data
        console.log("this.petDrinkList", this.petDrinkList)
        this.option2.xAxis.data = this.petDrinkList.map(item => item.createTime)
        this.option2.series[0].data = this.petDrinkList.map(item => item.water)
        console.log("this.option2", this.option2)
        this.changeIndex(0)
        this.initChart2();
      })
    },

    // 切换宠物时触发
    changeIndex(index) {
      this.selected = index;
      let petId = this.petInfo[index].petId;
      this.queryData.petId = petId
      this.petActivity = this.petActivityList.find(item => item.petId === petId)
      this.petDrink = this.petDrinkList.find(item => item.petId === petId)
      this.query(this.queryData.dateRange === '' ? 30 : this.queryData.dateRange)
    },
    //
    getPetDrinkInfoByIndex(index) {

    },
    getPetInfo: function () {
      getPetListAPI().then(res => {
        this.petInfo = res.data.map(item => {
          const updatedItem = {...item}; //
          updatedItem.personalityTrait = updatedItem.personalityTraits.split(';');
          if (updatedItem.imgs && updatedItem.imgs.includes(';')) {
            updatedItem.phtos = updatedItem.imgs.split(';');
          }
          updatedItem.dateOfBirth = parseTime2(updatedItem.dateOfBirth);
          return updatedItem;
        });
      });
    }
  },
  mounted() {
    this.initChart();
    this.initChart2();
    this.getPetInfo()
    this.query(30);
    this.getPetActivities()
    this.getDrink()
  }
}
</script>
<style>
.healthInfo_contain {
  margin-left: 7%;
  margin-right: 7%;
  background: rgba(211, 211, 211, 0.27);
}

.healthInfo_title {
  display: flex;
}

.healthInfo_statistics {
  margin-top: 2%;
}

.healthInfo_record {

  display: flex;
  flex: 1 1 50%;

}

.healthInfo_remind {

}

.pet_cover_imgs {
  object-fit: cover;
  height: 45px;
  width: 45px;
  border-radius: 20px;
  border: #a7b1bb solid 2px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: transform 90ms ease;
}

.pet_cover_imgs:hover {
  cursor: pointer;
  transform: scale(1.1);
  transition: height 300ms ease, transform 300ms ease; /* 过渡动画 */

}

.pet_cover_imgs:hover {
  transform: translateY(0);
}

.pet_cover_imgs:not(:hover) {
  transform: translateY(-25px);
}

.coverImg {
  overflow: hidden; /* 隐藏超出部分 */
}

.statistic_input {
  width: 80px;
  border: none !important; /* 移除所有边框 */
}

.statistic_input::placeholder {
  color: #000000;
  font-weight: normal;
  font-size: 16px;
}

.statistic_input:focus::placeholder {
  opacity: 0; /* 隐藏 placeholder */
  color: transparent; /* 可选：确保 placeholder 完全透明 */
}

.statistic_button {
  cursor: pointer;
  margin-right: 10px;
  background: rgba(176, 176, 176, 0.18);
  padding: 5px;
  width: 80px;
  text-align: center;
}

</style>